#!/usr/bin/python
from time import sleep
from multiprocessing import Process, Queue

from mqtt_class import WuxiMqttClass
from client_class import SocketClientClass
from old_service import Audio, Light
import random

broker = '192.168.211.165'
port = 1883
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'


def mq_run():
    mq = WuxiMqttClass(broker=broker, port=port, client_id=client_id)
    # print(mq)
    mq.subscribe_topic_received('wuxi/#')
    mq.client.loop_forever()


def tcp_run(ad):
    server_address = ('192.168.211.165', 8080)
    client = SocketClientClass(server_address)
    client.connect()
    am = Queue()
    while True:
        # message = 'Hello, server!'  # 调用接口得到信息部分
        # client.send(message)
        # if not aq.empty():
        #     content = aq.get()
        #     client.send(str(content))
        # else:
        #     break
        ad.getAudioData(am)
        print(am.qsize())
        content = am.get()
        print(content)
        client.send(content)

    response = client.receive()
    print(response)
    client.close()

if __name__ == '__main__':
    aq = Queue()
    audio = Audio()
    audio.start()
    light = Light()
    light.start(audio)
    # audio.getAudioData(aq)

    p1 = Process(target=mq_run, args=())
    p2 = Process(target=tcp_run, args=(audio,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
